<template>
  <div class="workflow-edit">
    <!-- 顶部导航 -->
    <div class="page-header">
      <div class="left">
        <el-button icon="Back" @click="cancel">返回</el-button>
        <el-divider direction="vertical" />
        <h2>{{ isEdit ? '编辑工作流' : '新建工作流' }}</h2>
      </div>
      <div class="right">
        <el-button-group>
          <el-button @click="cancel">取消</el-button>
          <el-button 
            type="primary" 
            :loading="saving"
            @click="save"
          >
            保存
          </el-button>
          <el-button 
            type="success"
            :loading="executing"
            :disabled="!formData.category || saving"
            @click="execute"
          >
            立即执行
          </el-button>
        </el-button-group>
      </div>
    </div>

    <div class="main-content">
      <el-form 
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="form-container"
      >
        <!-- 左侧：基本信息和参数配置 -->
        <div class="left-panel">
          <!-- 基本信息 -->
          <el-card class="section">
            <template #header>
              <div class="card-header">
                <span>基本信息</span>
              </div>
            </template>
            
            <el-form-item label="名称" prop="name">
              <el-input 
                v-model="formData.name" 
                placeholder="请输入工作流名称"
              />
            </el-form-item>

            <el-form-item label="类型" prop="category">
              <el-select 
                v-model="formData.category" 
                placeholder="请选择工作流类型"
                @change="handleCategoryChange"
              >
                <el-option
                  v-for="item in TEMPLATE_CATEGORIES"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                >
                  <el-icon><component :is="item.icon" /></el-icon>
                  <span>{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                :rows="3"
                placeholder="请输入工作流描述"
              />
            </el-form-item>
          </el-card>

          <!-- 参数配置 -->
          <el-card 
            v-if="formData.category" 
            class="section"
            :class="{ 'has-preset': showPresetPanel }"
          >
            <template #header>
              <div class="card-header">
                <span>参数配置</span>
                <el-button 
                  link 
                  type="primary"
                  @click="togglePresetPanel"
                >
                  {{ showPresetPanel ? '隐藏预设' : '显示预设' }}
                </el-button>
              </div>
            </template>

            <param-form
              v-model="formData.params"
              :template="currentTemplate"
              @change="handleParamsChange"
            />
          </el-card>
        </div>

        <!-- 右侧：预设和预览 -->
        <div 
          v-if="showPresetPanel && formData.category" 
          class="right-panel"
        >
          <el-card class="preset-panel">
            <template #header>
              <div class="card-header">
                <span>预设推荐</span>
              </div>
            </template>

            <div class="preset-list">
              <div 
                v-for="preset in categoryPresets"
                :key="preset.id"
                class="preset-item"
                @click="applyPreset(preset)"
              >
                <el-image 
                  :src="preset.preview_image"
                  fit="cover"
                />
                <div class="preset-info">
                  <h4>{{ preset.name }}</h4>
                  <p>{{ preset.description }}</p>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 预览 -->
          <el-card v-if="previewImage" class="preview-panel">
            <template #header>
              <div class="card-header">
                <span>效果预览</span>
              </div>
            </template>

            <div class="preview-content">
              <el-image :src="previewImage" fit="contain" />
            </div>
          </el-card>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useWorkflowStore } from '@/stores/workflow'
import { useTemplateStore } from '@/stores/template'
import { TEMPLATE_CATEGORIES } from '@/config/template'
import ParamForm from '@/components/ParamForm.vue'
import { usePresetStore } from '@/stores/preset'

const route = useRoute()
const router = useRouter()
const workflowStore = useWorkflowStore()
const templateStore = useTemplateStore()
const presetStore = usePresetStore()

const isEdit = computed(() => route.params.id !== undefined)
const formRef = ref()
const previewImage = ref('')

// 表单数据
const formData = ref({
  name: '',
  category: '',
  description: '',
  params: {}
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ]
}

// 获取当前模板
const currentTemplate = computed(() => {
  if (!formData.value.category) return null
  return templateStore.getBaseTemplate(formData.value.category)
})

// 状态控制
const saving = ref(false)
const executing = ref(false)
const showPresetPanel = ref(true)

// 获取当前分类的预设
const categoryPresets = computed(() => {
  if (!formData.value.category) return []
  return presetStore.getPresetsByCategory(formData.value.category)
})

// 切换预设面板
const togglePresetPanel = () => {
  showPresetPanel.value = !showPresetPanel.value
}

// 应用预设
const applyPreset = async (preset: any) => {
  try {
    const result = await presetStore.applyPreset(preset.id, formData.value.params)
    formData.value.params = result
    ElMessage.success('应用预设成功')
  } catch (error) {
    ElMessage.error('应用预设失败')
  }
}

// 处理类型变更
const handleCategoryChange = () => {
  formData.value.params = {}
  previewImage.value = ''
}

// 处理参数变更
const handleParamsChange = async (params: any) => {
  // TODO: 调用预览API
  console.log('params changed:', params)
}

// 保存
const save = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    saving.value = true
    
    if (isEdit.value) {
      await workflowStore.updateWorkflow(route.params.id as string, formData.value)
      ElMessage.success('更新成功')
    } else {
      await workflowStore.createWorkflow(formData.value)
      ElMessage.success('创建成功')
    }
    
    router.push('/workflow/list')
  } catch (error) {
    console.error(error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 执行
const execute = async () => {
  try {
    executing.value = true
    const result = await workflowStore.executeWorkflow(
      isEdit.value ? route.params.id as string : '',
      formData.value
    )
    // 处理执行结果
    previewImage.value = result.output_image
  } catch (error) {
    ElMessage.error('执行失败')
  } finally {
    executing.value = false
  }
}

// 取消
const cancel = () => {
  router.back()
}

// 初始化
const init = async () => {
  if (isEdit.value) {
    try {
      const workflow = await workflowStore.getWorkflow(route.params.id as string)
      formData.value = {
        name: workflow.name,
        category: workflow.category,
        description: workflow.description,
        params: workflow.params || {}
      }
    } catch (error) {
      ElMessage.error('获取工作流信息失败')
      router.push('/workflow/list')
    }
  }
}

init()
</script>

<style scoped>
.workflow-edit {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-header {
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-light);
  background: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header .left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-header h2 {
  margin: 0;
}

.main-content {
  flex: 1;
  padding: 20px;
  background: var(--el-bg-color-page);
  overflow: auto;
}

.form-container {
  display: flex;
  gap: 20px;
  height: 100%;
}

.left-panel {
  flex: 1;
  min-width: 0;
}

.right-panel {
  width: 300px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.section {
  margin-bottom: 20px;
}

.section.has-preset {
  margin-right: 320px;
}

.preset-panel,
.preview-panel {
  position: sticky;
  top: 20px;
}

.preset-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 400px;
  overflow-y: auto;
}

.preset-item {
  display: flex;
  gap: 10px;
  padding: 10px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.preset-item:hover {
  border-color: var(--el-color-primary);
  transform: translateX(5px);
}

.preset-item .el-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.preset-info {
  flex: 1;
  min-width: 0;
}

.preset-info h4 {
  margin: 0 0 8px;
}

.preset-info p {
  margin: 0;
  color: #666;
  font-size: 13px;
}

.preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.preview-content .el-image {
  max-width: 100%;
  max-height: 400px;
}
</style> 